<template>
  <AppDialogForm
    title="分配角色"
    :confirm="handleSubmit"
    @closed="handleDialogClosed"
    @open="handleDialogOpen"
  >
    <el-form
      ref="form"
      :model="formData"
      label-width="100px"
      v-loading="loading"
    >
      <el-form-item label="当前的用户">
        <p>{{ userInfo.username }}</p>
      </el-form-item>
      <el-form-item label="当前的角色">
        <p>{{ userInfo.role_name }}</p>
      </el-form-item>
      <el-form-item label="分配新角色" prop="roleId">
        <el-select v-model="formData.roleId" placeholder="请选择管理员身份">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
  </AppDialogForm>
</template>

<script setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { setRoles } from "@/api/user.js";

const props = defineProps({
  userInfo: {
    type: Object,
    default: () => {},
  },
  rolesList: {
    type: Array,
    default: () => [],
  },
});
const emit = defineEmits(["success"]);
const form = ref(null);
const loading = ref(false);
const formData = ref({
  id: "",
  roleId: "",
});

const handleDialogOpen = () => {
  formData.value = {
    id: props.userInfo.id,
    roleId: "",
  };
};

const handleSubmit = async () => {
  const valid = await form.value.validate();
  if (!valid) {
    return;
  }
  loading.value = true;
  await setRoles(formData.value).finally(() => {
    loading.value = false;
  });
  ElMessage.success("更新角色成功");
  emit("success");
};
const handleDialogClosed = () => {
  form.value.clearValidate(); // 清除验证结果
  form.value.resetFields(); // 清除表单数据
  formData.value = {
    id: "",
    roleId: "",
  };
};
</script>

<style lang="scss" scoped></style>
